package org.a1.ectltool.boundary;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.a1.ectltool.control.DWHManager;
import org.a1.ectltool.control.FileReader;
import org.a1.ectltool.control.KoffieBestandEuro2007TextReader;
import org.a1.ectltool.control.KoffieBestandEuro20082009ExcelReader;

/**
 * The main frame of the ECTLTool
 * @author Jeffrey Goudzwaard
 * @version 1.0
 * @since 11-12-1013
 */
public class MainFrame extends JFrame implements WindowListener
{
	private static final long serialVersionUID = 192666363140837026L;
	
	//The title of the frame
	private static final String TITLE = "ECTL Tool A1";
	
	//The size of the frame
	private static final Dimension SIZE = new Dimension(400, 400);
	
	private JFileChooser jfcFile;
	
	//The instance of the MainFrame, we are using the singleton pattern
	private static volatile MainFrame INSTANCE;
	
	//The button for opening the source file
	private JButton btnOpen;
	
	//The text area for logging
	private JTextArea txaLog;
	
	//The scroll pane for the logging area
	private JScrollPane jspScrollPane;
	
	//The label for the logger
	private JLabel lblLogger;
	
	//The format for the date
	private DateFormat dateFormat;
	
	
	//The file reader for reading the source files
	private FileReader reader;
	
	/**
	 * The default constructor
	 */
	private MainFrame()
	{	
		init();
		initGUI();
	}
	
	/**
	 * They way for using the singleton pattern
	 * @return INSTANCE the instance of the frame
	 */
	public static synchronized MainFrame getFrame()
	{
		if(INSTANCE == null)
		{
			INSTANCE = new MainFrame();
		}
		
		return INSTANCE;
	}
	
	/**
	 * Initializes the variables
	 */
	private void init()
	{
		//Setting the title
		setTitle(TITLE);
		
		//Setting the size of the frame
		setPreferredSize(SIZE);
		setSize(SIZE);
		
		//Make sure the user can't resize the frame
		setResizable(false);
		
		//Exit the program when closing the frame
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		//Start the application in the middle of the screen
		setLocationRelativeTo(null);
		
		//Make a new File Chooser
		jfcFile = new JFileChooser();
		
		//Make a new instance for the open button
		btnOpen = new JButton();
		
		//Make a new instance for the log area
		txaLog = new JTextArea();
		
		//Make a new instance for the scroll pane and add the log to it
		jspScrollPane = new JScrollPane(txaLog);
		
		//Make a new instance for the log label
		lblLogger = new JLabel();
		
		//Make a new instance for the simple date format and set the format for the date
		dateFormat = new SimpleDateFormat("<HH:mm:ss>: ");
		
		addWindowListener(this);
	}
	
	/**
	 * Initializes the GUI and puts everything together
	 */
	private void initGUI()
	{
		//Set layout manager to null so we can use point locations for the components
		setLayout(null);
		
		//The file dialog
		jfcFile.setMultiSelectionEnabled(false);
		
		//The label for the logger
		lblLogger.setText("Log");
		lblLogger.setSize(200, 20);
		lblLogger.setLocation(0, (SIZE.height / 2) - 45);
		
		//log text area
		txaLog.setSize(SIZE.width, (SIZE.height / 2) - 20);
		txaLog.setEditable(false);
		
		//Scroll pane for the log area
		jspScrollPane.setSize(SIZE.width, SIZE.height / 2);
		jspScrollPane.setLocation(0, (SIZE.height / 2) - 20);
		
		//Open button
		btnOpen.setText("Open bestand");
		btnOpen.setSize(200, 20);
		btnOpen.setLocation(20, 20);
		btnOpen.addActionListener(new ActionListener()
		{
			/**
			 * The function to be called when pressed on the open button
			 */
			@Override
			public void actionPerformed(ActionEvent ae)
			{
				addLog("Opening file...");
				
				int ret = jfcFile.showOpenDialog(INSTANCE);
				if(ret == JFileChooser.APPROVE_OPTION)
				{
					if(jfcFile.getSelectedFile().getName().equals("KoffieBestandEuro2007.txt"))
						reader = new KoffieBestandEuro2007TextReader(jfcFile.getSelectedFile());
					else if(jfcFile.getSelectedFile().getName().equals("KoffieBestandEuro20082009.xlsx"))
						reader = new KoffieBestandEuro20082009ExcelReader(jfcFile.getSelectedFile());
					else
					{
						addLog("Unsupported file!");
						showMessage("Unsupported file!", "This file is not supported!\r\nPlease pick another file", JOptionPane.ERROR_MESSAGE);
						return;
					}
					
					//Make sure the reader isn't null
					if(reader != null)
					{
						reader.extract();
						reader.clean();
						reader.transform();
						reader.load();
					}
				}
				else if(ret == JFileChooser.CANCEL_OPTION)
					addLog("Canceled!");
				else if(ret == JFileChooser.ERROR_OPTION)
					addLog("Failed!");
			}
		});
		
		//Add the components to the frame
		add(lblLogger);
		add(jspScrollPane);
		add(btnOpen);
	}
	
	/**
	 * Packs all the components together and displays the frame
	 */
	public void showFrame()
	{
		addLog("Displaying frame...");
		pack();
		setVisible(true);
		addLog("Done!");
	}
	
	/**
	 * Adds a new line to the logger with the current day and date
	 * @param msg the message to add to the logger
	 */
	public void addLog(String msg)
	{
		Date now = new Date();
		txaLog.append(dateFormat.format(now) + msg + "\r\n");
		txaLog.setCaretPosition(txaLog.getDocument().getLength());
	}
	
	/**
	 * Shows a message in a dialog with a title and Icon
	 * @param title the title of the message
	 * @param message the message to show
	 * @param messageType the icon to show
	 */
	public void showMessage(String title, String message, int messageType)
	{
		JOptionPane.showMessageDialog(null, message, title, messageType);
	}

	@Override
	public void windowActivated(WindowEvent we)
	{
	}

	@Override
	public void windowClosed(WindowEvent we)
	{
	}

	@Override
	public void windowClosing(WindowEvent we)
	{
		DWHManager.getManager().stop();
	}

	@Override
	public void windowDeactivated(WindowEvent we)
	{
	}

	@Override
	public void windowDeiconified(WindowEvent we)
	{
	}

	@Override
	public void windowIconified(WindowEvent we)
	{
	}

	@Override
	public void windowOpened(WindowEvent we)
	{
	}
}
